package com.chuangke.admin.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chuangke.admin.dao.SysRoleMenuDaoService;
import com.chuangke.admin.entity.SysRoleMenu;
import com.chuangke.admin.service.SysRoleMenuService;
import com.chuangke.common.constant.CacheKeyConstants;
import com.chuangke.common.idgen.IdManager;
import com.chuangke.common.utils.BusinessUtil;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SysRoleMenuServiceImpl implements SysRoleMenuService {

	@Autowired
	private SysRoleMenuDaoService sysRoleMenuDaoService;

	@Cacheable(cacheNames = CacheKeyConstants.SYS_ROLE_MENU, key = "'" + CacheKeyConstants.SYS_ROLE_MENU + "'")
	@Override
	public List<SysRoleMenu> findList() {
        return sysRoleMenuDaoService.list();
	}

	@Override
	public Map<String, List<SysRoleMenu>> findMap() {
		List<SysRoleMenu> allList = ((SysRoleMenuService) AopContext.currentProxy()).findList();
		return allList.stream().collect(Collectors.groupingBy(SysRoleMenu::getRoleId));
	}

	@CacheEvict(cacheNames = CacheKeyConstants.SYS_ROLE_MENU, key = "'" + CacheKeyConstants.SYS_ROLE_MENU + "'")
	@Override
	public void deleteByRoleId(String roleid) {
		sysRoleMenuDaoService.remove(new QueryWrapper<SysRoleMenu>().lambda().eq(SysRoleMenu::getRoleId, roleid));
	}

	@CacheEvict(cacheNames = CacheKeyConstants.SYS_ROLE_MENU, key = "'" + CacheKeyConstants.SYS_ROLE_MENU + "'")
	@Override
	public void insert(List<SysRoleMenu> list) {
		list.forEach(item -> {
			if (BusinessUtil.isInsert(item.getId())) {
				item.setId(IdManager.nextId());
			}
		});
//		for (SysRoleMenu record : list) {
//			sysRoleMenuDaoService.save(record);
//		}
		sysRoleMenuDaoService.saveBatch(list) ;
	}

	@Override
	public List<SysRoleMenu> findByRoleId(String id) {
		if (StrUtil.isBlank(id)) {
			return new ArrayList<>();
		}
		
		Map<String, List<SysRoleMenu>> map = ((SysRoleMenuService) AopContext.currentProxy()).findMap();
		return map.get(id);
	}

	@Override
	public List<SysRoleMenu> findByMenuId(String id) {
		if (StrUtil.isBlank(id)) {
			return new ArrayList<>();
		}
		
		List<SysRoleMenu> allList = ((SysRoleMenuService) AopContext.currentProxy()).findList();
		return allList.stream().filter(sm -> id.equals(sm.getMenuId())).collect(Collectors.toList());
	}

}
